<template>
  <section class="todoapp">
    <todo-header @todoName="todoName"></todo-header>
    <todo-main
      :list="mainList"
      @delTodo="delTodo"
      @checkbox="checkbox"
      @allCheck="allCheck"
    ></todo-main>
    <todo-footer
      :list="list"
      @clearList="clearList"
      @changeType="changeType"
    ></todo-footer>
  </section>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  components: { TodoFooter, TodoHeader, TodoMain },
  data() {
    return {
      //||在或中,如果前面为假,就直接执行后面的
      list: JSON.parse(localStorage.getItem("list")) || [],
      type: "all",
    };
  },
  methods: {
    delTodo(id) {
      const index = this.list.findIndex((item) => {
        return item.id === id;
      });

      this.list.splice(index, 1);
    },
    todoName(todoadd) {
      // this.list.splice(0, 0, todoadd);
      this.list.unshift(todoadd);
    },
    clearList() {
      this.list = this.list.filter((item) => {
        return !item.isDone;
      });
    },
    checkbox(id) {
      const obj = this.list.find((item) => {
        return item.id === id;
      });
      obj.isDone = !obj.isDone;
    },
    changeType(val) {
      this.type = val;
    },
    allCheck(val) {
      this.list.forEach((item) => {
        item.isDone = val;
      });
    },
  },
  computed: {
    mainList() {
      if (this.type === "all") {
        return this.list;
      } else if (this.type === "active") {
        return this.list.filter((item) => {
          return !item.isDone;
        });
      } else {
        return this.list.filter((item) => {
          return item.isDone;
        });
      }
      // return this.list;
    },
  },
  watch: {
    list: {
      //深度监听
      deep: true,
      handler(list) {
        localStorage.setItem("list", JSON.stringify(list));
      },
    },
  },
};
</script>

<style lang="less" scoped>
</style>